import axios from 'axios'
import { ref, inject } from 'vue'
import { getKWMusicService, getWYYMusicService } from '@/api/music'
import { usePlayListStore } from '@/stores'
export const useMusicCell = () => {
  const musicPlayer = inject('musicPlayerRef')

  const playListStore = usePlayListStore()
  const getMusic = async (musicInfo) => {
    if (musicInfo.msg && musicInfo.rid) {
      const musics = await getWYYMusicService({
        msg: musicInfo.msg,
        rid: musicInfo.rid
      })
      if (musics.data.mp3 === undefined) {
        showFailToast('服务异常')
        new Error('musics.data.mp3为空')
      }
      return {
        ...musicInfo,
        name: musics.data.name,
        singer: musics.data.author,
        album: '',
        cover: musics.data.img,
        audio_url: musics.data.mp3
      }
    } else {
      const musicUrl = await getKWMusicService(
        musicInfo.DC_TARGETID || musicInfo.rid
      )
      if (musicInfo.audio_url === undefined) {
        return {
          name: musicInfo.NAME,
          singer: musicInfo.ARTIST,
          album: musicInfo.ALBUM,
          cover: musicInfo.hts_MVPIC,
          rid: musicInfo.DC_TARGETID,
          audio_url: musicUrl.data
        }
      } else {
        return { ...musicInfo, audio_url: musicUrl.data }
      }
    }
  }
  // 添加音乐 1.音乐的索引 2.是否立即播放
  // 1 立即播放 0 等待播放
  const addMusic = async (musicInfo, isPlay) => {
    console.log(musicInfo)

    // const music = await getMusic({
    //   album: '孤勇者',
    //   audio_url:
    //     'http://lv.sycdn.kuwo.cn/d7b465624e57c819d2dff401d85f1578/66e13735/resource/30106/trackmedia/M800001hE0cD4NPYfX.mp3',
    //   cover: 'https://img4.kuwo.cn/wmvpic/324/98/20/3867968181.jpg',
    //   name: '孤勇者',
    //   rid: '228908',
    //   singer: '陈奕迅'
    // })
    const music = await getMusic(musicInfo)
    musicPlayer.value.insertMusic([music])
    // musicPlayer.value.upWaitPlay()
    if (isPlay === 0) {
      showNotify({ type: 'primary', message: '成功添加至下一首播放' })
    } else {
      showNotify({
        type: 'primary',
        message: '正在播放：' + music.name + ' - ' + music.singer
      })
      musicPlayer.value.onNext()
    }
  }
  // 收藏
  const addLike = async (musicArr, arr) => {
    if (musicArr.length === 1) {
      const music = await getMusic(musicArr[0])
      playListStore.addListItem([music], arr)
    } else if (musicArr.length > 1) {
      playListStore.addListItem(musicArr, arr)
    }
    showSuccessToast('收藏成功')
  }

  // 复制
  // async function copyToClipboard(text) {
  //   try {
  //     await navigator.clipboard.writeText(text);
  //     console.log('Copied to clipboard: ', text);
  //   } catch (err) {
  //     console.error('Failed to copy to clipboard: ', err);
  //   }
  // }

  function copyToClipboard(text) {
    const input = document.createElement('input')
    input.setAttribute('value', text)
    document.body.appendChild(input)
    input.select()
    document.execCommand('copy')
    document.body.removeChild(input)
  }
  // 用于移动app
  // const downloadFile = async (musicInfo) => {
  //   const music = await getMusic(musicInfo)
  //   const fileName = music.singer + ' - ' + music.name + '.mp3' // 设置文件名
  //   copyToClipboard(fileName)
  //   plus.runtime.openURL(music.audio_url) // Hbuilder提供的第三方插件
  // }
  // 用于Nginx
  const downloadFile = async (musicInfo) => {
    const music = await getMusic(musicInfo)
    // const link = document.createElement('a')
    // link.href = music.audio_url
    const fileName = music.singer + ' - ' + music.name + '.mp3' // 设置文件名
    // link.download = fileName
    copyToClipboard(fileName)
    // link.click()
    // link.remove() // 清理 DOM

    window.open(music.audio_url)
  }

  /*
   * 音乐下载 - 需跨域
   */
  // const fileURL = ref(null)
  // const downloadFile = async (musicInfo) => {
  //   const music = await getMusic(musicInfo)
  //   try {
  //     const response = await axios({
  //       url: music.audio_url,
  //       method: 'GET',
  //       responseType: 'blob'
  //       // onDownloadProgress: (progressEvent) => {
  //       //   const percentCompleted = Math.round(
  //       //     (progressEvent.loaded * 100) / progressEvent.total
  //       //   )
  //       //   progress.value = percentCompleted
  //       // }
  //       // 进度条
  //     })
  //     const blob = new Blob([response.data], { type: 'audio/mpeg' })
  //     fileURL.value = URL.createObjectURL(blob)
  //     console.log(fileURL.value)

  //     // Create a temporary link element to trigger the download
  //     const link = document.createElement('a')
  //     link.href = fileURL.value

  //     link.download = music.singer + ' - ' + music.name + '.mp3'
  //     link.click()
  //     link.remove() // 清理 DOM

  //     // Simulate pause and resume functionality
  //   } catch (error) {
  //     showFailToast('服务异常')
  //     console.error('Error during download:', error)
  //     // isDownloading.value = false
  //   }
  // }

  return {
    getMusic,
    addMusic,
    addLike,
    downloadFile,
    copyToClipboard
  }
}
